// 状态卡
class HaCloudMusicPlayer extends HTMLElement {

    constructor() {
        super()
        // 播放模式
        this.playMode = [
            {
                name: '列表循环',
                value: 0,
                icon: 'mdi:repeat'
            },
            {
                name: '顺序播放',
                value: 1,
                icon: 'mdi:shuffle-disabled'
            },
            {
                name: '随机播放',
                value: 2,
                icon: 'mdi:shuffle'
            },
            {
                name: '单曲循环',
                value: 3,
                icon: 'mdi:repeat-once'
            }
        ]
    }

    /*
     * 接收HA核心对象
     */
    set hass(hass) {
        this._hass = hass
        if (!this.isCreated) {
            this.created(hass)
        }
    }

    get stateObj() {
        return this._stateObj
    }

    // 接收当前状态对象
    set stateObj(value) {
        this._stateObj = value
        if (this.isCreated) this.updated()
    }

    // 创建界面
    created(hass) {
        /* ***************** 基础代码 ***************** */
        const shadow = this.attachShadow({ mode: 'open' });
        // 创建面板
        const ha_card = document.createElement('div');
        ha_card.className = 'more-info-state-ha_cloud_music'
        ha_card.innerHTML = `
        <div class="controls">
            <div>
                <ha-icon class="play_mode" icon="mdi:repeat" title="播放模式"></ha-icon>
            </div>
            <div>
                <ha-icon class="prev" icon="mdi:skip-previous" title="上一曲"></ha-icon>
            </div>
            <div>
                <img title="播放/暂停" class="action" style="height:80px;width:80px;border:1px solid silver;border-radius:50%;" src="" />
            </div>
            <div>
                <ha-icon class="next" icon="mdi:skip-next" title="下一曲"></ha-icon>
            </div>
            <div>
                <ha-icon class="controls-list" icon="mdi:refresh" title="重新播放"></ha-icon>
            </div>
        </div>
        <!-- 音乐进度 -->
        <div class="progress">
          <div><ha-icon class="mdi-cards-heart" icon="mdi:cards-heart" title="喜欢"></ha-icon></div>
          <div class="time-position">00:00</div>
          <div>
            <paper-slider
                class="ha-paper-slider"
                value="50"
                max="100"
                pin
                markers
                title="调整播放进度"
                style="flex: 1"
            ></paper-slider>
          </div>                 
          <div class="time-length">00:00</div>
          <div><ha-icon class="icon-music-search" icon="mdi:search-web" title="音乐搜索"></ha-icon></div>
        </div>
        <ha_cloud_music-search class="hide"></ha_cloud_music-search>
        `
        shadow.appendChild(ha_card)
        // 创建样式
        const style = document.createElement('style')
        style.textContent = `
            .hide{display:none;}
            .controls,
            .progress{ display:flex; text-align: center; align-items: center;}
            .controls>div,
            .progress>div{width:100%;}
            .red{color:red;}
            ha-icon,
            .action{
                cursor:pointer;
            }
            .controls ha-icon{--mdc-icon-size: 30px;}
            .mdi-cards-heart{
                --mdc-icon-size: 25px;
            }
            .icon-music-search{
                --mdc-icon-size: 30px;
                color: gray;
            }

            @keyframes rotate{
                from{ transform: rotate(0deg) }
                to{ transform: rotate(359deg) }
            }
            .rotate{
                animation: rotate 5s linear infinite;
            }
        `
        shadow.appendChild(style);
        // 保存核心DOM对象
        this.shadow = shadow
        this.$ = this.shadow.querySelector.bind(this.shadow)
        // 创建成功
        this.isCreated = true
        /* ***************** 附加代码 ***************** */
        let { $ } = this
        $('.prev').onclick = () => {
            ha_cloud_music.toast("上一曲")
            ha_cloud_music.callMediaPlayerService("media_previous_track")
        }
        $('.next').onclick = () => {
            ha_cloud_music.toast("下一曲")
            ha_cloud_music.callMediaPlayerService("media_next_track")
        }
        $('.action').onclick = () => {
            const { state } = this.stateObj
            ha_cloud_music.toast(state == "playing" ? '暂停音乐' : '播放音乐')
            ha_cloud_music.callMediaPlayerService("media_play_pause")
        }
        $('.controls-list').onclick = () => {
            ha_cloud_music.toast("重新开始播放")
            let { source } = this.stateObj.attributes
            if (source) ha_cloud_music.callMediaPlayerService("select_source", { source })
        }
        $('.play_mode').onclick = () => {
            let icon = $('.play_mode').getAttribute('icon')
            let obj = this.playMode.find(ele => ele.icon === icon)
            let mode = obj.value
            mode = mode >= 3 ? 0 : mode + 1
            // 设置播放模式
            ha_cloud_music.callService("ha_cloud_music.config", { play_mode: mode })

            let newMode = this.playMode[mode]
            ha_cloud_music.toast(newMode.name)
            $('.play_mode').setAttribute('icon', newMode.icon)

        }

        $('.progress .ha-paper-slider').onchange = () => {
            const { media_duration } = this.stateObj.attributes
            let seek_position = Math.floor($('.progress .ha-paper-slider').value / 100 * media_duration)
            ha_cloud_music.callMediaPlayerService("media_seek", { seek_position })
            ha_cloud_music.toast(`调整音乐进度到${seek_position}秒`)
        }

        $('.mdi-cards-heart').onclick = () => {
            $('.mdi-cards-heart').classList.add('red')
            ha_cloud_music.fetchApi({ type: 'love_set' }).then((res) => {
                ha_cloud_music.toast(res.msg)
                // 通知最爱列表更新
                ha_cloud_music.onmessage('love_set')
            })
        }
        $('.icon-music-search').onclick = () => {
            $('ha_cloud_music-search').classList.toggle('hide')
        }
    }

    // 更新界面数据
    updated() {
        let { $, _stateObj } = this
        // console.log(_stateObj)
        const { state, attributes } = _stateObj
        const { entity_picture, favourite, play_mode, media_position, media_duration } = attributes
        // 封面播放图
        const action = $('.action')
        if (entity_picture) {
            action.src = entity_picture
        }
        // 如果是在播放中，则转圈圈
        if (state == "playing") {
            if (!action.classList.contains('rotate')) action.classList.add('rotate')
        } else {
            action.classList.remove('rotate')
        }
        // 判断是否红心
        const classList = $('.mdi-cards-heart').classList
        const isFavourite = classList.contains('red')
        if (favourite) {
            if (!isFavourite) classList.add('red')
        } else {
            if (isFavourite) classList.remove('red')
        }
        // 设备模式
        let mode = this.playMode.find(ele => ele.name == play_mode)
        if (mode) {
            $('.play_mode').setAttribute('icon', mode.icon)
        }
        $('.progress .time-position').textContent = `${this.timeForamt(media_position / 60)}:${this.timeForamt(media_position % 60)}`
        $('.progress .time-length').textContent = `${this.timeForamt(media_duration / 60)}:${this.timeForamt(media_duration % 60)}`
        if (media_position <= media_duration) {
            $('.progress .ha-paper-slider').value = media_position / media_duration * 100
        }
    }

    timeForamt(num) {
        if (isNaN(num)) return '00'
        num = Math.floor(num)
        if (num < 10) return '0' + String(num)
        return String(num)
    }
}

// 定义DOM对象元素
customElements.define('ha_cloud_music-player', HaCloudMusicPlayer);